package serializer

import (
	"context"
	"fmt"
	"reflect"
	"time"

	"gorm.io/gorm/schema"
)

const (
	dateDefault = "1970-01-01"
)

// DateSerializer date序列化器
type DateSerializer struct {
}

// 实现 Scan 方法
func (DateSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error) {
	value := ""
	if dbValue != nil {
		switch v := dbValue.(type) {
		case []byte:
			value = string(value)
		case string:
			value = v
		case time.Time:
			value = v.Format(time.DateOnly)
		default:
			return fmt.Errorf("failed to date value: %#v", dbValue)
		}
	}

	if value == dateDefault {
		value = ""
	}

	err = field.Set(ctx, dst, value)
	return
}

// 实现 Value 方法
func (DateSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error) {
	value := dateDefault
	switch v := fieldValue.(type) {
	case string:
		if v != "" {
			value = v
		}
	}

	return value, nil
}
